# @Time : 2019/12/16 17:26 
# @Author : Fioman 
# @Phone : 13149920693

"""
从来解析XML文件的一个Python模块,包括XML的读和写
"""
import time
from xml.dom.minidom import parse, Document


# 获取通信标识符
def get_transaction_id():
    now_second = time.time()
    last_three = str(now_second).split('.')[1][:3]
    now = time.strftime("%Y%m%d%H%M%S", time.localtime(now_second))
    transaction_id = now + last_three
    return transaction_id


def readXML():
    dom_tree = parse('./message.xml')
    # 文档根元素
    rootNode = dom_tree.documentElement
    print(rootNode)

# messagename的值,以及body节点类型的字典.
def pack_send_message(head_msg_name, body, ret):
    print('in pack_send_message: head_msg_name = {}'.format(head_msg_name))
    doc = Document()  # 在内存中创建的一个空的文档
    root = doc.createElement('message')  # 创建根节点
    doc.appendChild(root)  # 将根节点添加到文档对象中

    # 然后将head的消息和body的消息以及ret的消息填入.
    head_node = doc.createElement('head')
    msg_name_node = doc.createElement('messagename')
    msg_name_node.appendChild(doc.createTextNode(head_msg_name))
    transaction_id = get_transaction_id()
    id_node = doc.createElement('transactionid')
    id_node.appendChild(doc.createTextNode(transaction_id))
    head_node.appendChild(msg_name_node)
    head_node.appendChild(id_node)

    body_node = doc.createElement('body')
    if head_msg_name != "Trace Data Reply":
        for element, value in body.items():
            node = doc.createElement(element)
            node.appendChild(doc.createTextNode(value))
            body_node.appendChild(node)
    else:
        for item in body:
            trace_list_node = doc.createElement("trace_data_list")
            data_no_node = doc.createElement('data_no')
            data_item_node = doc.createElement('data_item')
            data_value_node = doc.createElement('data_value')
            data_no_node.appendChild(doc.createTextNode(item[0]))
            data_item_node.appendChild(doc.createTextNode(item[1]))
            data_value_node.appendChild(doc.createTextNode(item[2]))
            trace_list_node.appendChild(data_no_node)
            trace_list_node.appendChild(data_item_node)
            trace_list_node.appendChild(data_value_node)
            body_node.appendChild(trace_list_node)

    ret_node = doc.createElement('return')
    for element, value in ret.items():
        node = doc.createElement(element)
        if value != "":
            node.appendChild(doc.createTextNode(value))
        ret_node.appendChild(node)

    root.appendChild(head_node)
    root.appendChild(body_node)
    root.appendChild(ret_node)
    if head_msg_name == 'Are You There Request':
        fp1 = open(r'./ask_msg.xml','w')
        doc.writexml(fp1, indent='', addindent='\t', newl='\n', encoding='utf-8')
        fp1.close()
    else:
        fp2 = open(r'./send_msg.xml', 'w')
        doc.writexml(fp2, indent='', addindent='\t', newl='\n', encoding='utf-8')
        fp2.close()

# 解析接收到的消息
def parse_recv_msg(msg_recv):
    if msg_recv == 'MESSAGE_ERROR':
        return None,None
    write_recv_message(msg_recv) # 将消息写入到XML文件中
    dom = parse(r'./message_recv.xml')
    root_node = dom.documentElement
    msg_name_node = root_node.getElementsByTagName("messagename")[0]
    body_dict = {}
    body_node = root_node.getElementsByTagName("body")[0]
    for node in body_node.childNodes:
        if node.nodeName != "#text":
            body_dict[node.nodeName] = node.childNodes[0].data
    ret_node = root_node.getElementsByTagName("returncode")[0]
    msg_name = msg_name_node.childNodes[0].data
    ret = ret_node.childNodes[0].data
    print('in parse_recv_msg,msg_recv = {} ,msg_name = {},ret = {}'.format(msg_recv,msg_name,ret))
    return msg_name,body_dict,ret

# 获取要发送的消息内容
def get_send_msg():
    with open(r'./send_msg.xml','rb') as f:
        data = f.read()
    msg = bytes(chr(2),encoding='ascii')+ data + bytes(chr(3),encoding='ascii')
    print("msg:{}".format(msg))
    return msg

# 将接受到的消息,写入到XML文件中.
def write_recv_message(message_recv):
    with open("./message_recv.xml", "wb") as f:
        f.write(message_recv[1:-1])


if __name__ == '__main__':
    # get_transaction_id()
    # readXML()

    # with open("./message_send.xml", 'rb') as f:
    #     message = f.read()
    #     message = b'Char(2)' + message + b'Char(3)'
    #     print(len(message))
    #     write_recv_message(message)

    # head_msg_name = 'Are you There'
    # body = {
    #     "user_id": "ID002",
    #     "server_ip":"192.168.1.1"
    # }
    #
    # ret = {
    #     "returncode":"0",
    #     "returnmessage":"",
    # }
    #
    # pack_send_message(head_msg_name,body,ret)
    #
    # get_send_msg()
    dom = parse('./server_send.xml')
    root_node = dom.documentElement
    body_node = root_node.getElementsByTagName('body')[0]
    body_dict = {}
    print(type(body_node))
    for node in body_node.childNodes:
        if node.nodeName != "#text":
            body_dict[node.nodeName] = node.childNodes[0].data

    for node_name,node_value in body_dict.items():
        print(node_name,node_value)
